/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2016 abel533@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package tk.mybatis.springboot.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.mapper.util.StringUtil;
import tk.mybatis.springboot.model.TSysUser;
import tk.mybatis.springboot.service.SysUserService;
import tk.mybatis.springboot.util.RedisUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {
    Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private SysUserService userService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 扫码创建管理员(样例：http://localhost:8090/user/createManager?openId=wx12345&role=0)
     *
     * @param tSysUser
     * @return
     */
    @RequestMapping(value = "/createManager")
    public ModelAndView add(TSysUser tSysUser) {
        ModelAndView modelAndView = new ModelAndView("bindresult");
        if (!StringUtil.isEmpty(tSysUser.getOpenId())) {
            tSysUser.setCreateTime(new Date());
            tSysUser.setRolo(tSysUser.getRolo());
            userService.save(tSysUser);
            modelAndView.addObject("message", "绑定成功");
        } else {
            modelAndView.addObject("message", "绑定失败,未获取到openid");
        }

        return modelAndView;
    }

    /**
     * 登陆页面
     *
     * @return
     */
    @RequestMapping(value = "/loginIndex")
    public ModelAndView loginPage() {
        ModelAndView modelAndView = new ModelAndView("lockscreen");
        ArrayList<TSysUser> tSysUsers = (ArrayList<TSysUser>) userService.getAll(new TSysUser());
        modelAndView.addObject("sysUsers", tSysUsers);
        return modelAndView;
    }

    /**
     * 登陆验证
     *
     * @return
     */
    @RequestMapping(value = "/login")
    public TSysUser login(TSysUser tSysUser, HttpServletRequest request) {
        TSysUser user = userService.getUser(tSysUser);
        if (user != null) {
            log.info("登陆成功");
            HttpSession session = request.getSession();
            session.setAttribute("sysuser", user);
        } else {
            log.info("登陆失败");
        }
        return user;
    }

    @RequestMapping(value = "/logout")
    public ModelAndView loginOut(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("redirect:/user/loginIndex");
        request.getSession().removeAttribute("sysuser");
        return modelAndView;
    }

    private String getRandomUser() {
        String qrcode = "http://192.168.102.155:8090/user/scanLogin?openId=";
        List<TSysUser> tSysUsers = userService.getAll(new TSysUser());
        Random random = new Random(tSysUsers.size());
        TSysUser randomUser = tSysUsers.get(random.nextInt(tSysUsers.size()));
        qrcode += randomUser.getOpenId();
        log.info("登陆二维码:{}", qrcode);
        return qrcode;
    }

    /**
     * 管理员扫码登陆(样例：http://localhost:8090/user/scanLogin?openId=wx12345)
     *
     * @param tSysUser
     * @return
     */
    @RequestMapping(value = "/scanLogin")
    public ModelAndView scanLogin(TSysUser tSysUser) {
        ModelAndView modelAndView = new ModelAndView("bindresult");
        if (!StringUtil.isEmpty(tSysUser.getOpenId())) {
            TSysUser sysUser = userService.getUser(tSysUser);
            if (sysUser != null) {
                log.info("登陆成功");
                String token = DigestUtils.md5Hex(UUID.randomUUID().toString());
                redisUtil.set(tSysUser.getOpenId(), token);
                log.info(String.format("key:%s,value:%s", tSysUser.getOpenId(), token));
                modelAndView.addObject("message", "登陆成功");
            } else {
                log.info("登陆失败");
                modelAndView.addObject("message", "登陆失败");
            }
        } else {
            log.info("openid未获取");
            modelAndView.addObject("message", "登陆失败");
        }
        return modelAndView;
    }
}
